﻿using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class SearchFriendPanel : BasePanel
{

	public Button cancelBtn;

	public Button searchBtn;

	public InputField keyWordInputTextField;


	private SearchFriendRequest _searchFriendRequest;

	private GameObject _searchItemPrefab;//搜索结果项预制体
	// Use this for initialization
	void Start () {
		
		//组件初始化
		_searchFriendRequest = this.gameObject.GetComponent<SearchFriendRequest>();
		_searchItemPrefab = Resources.Load<GameObject>("UIPanel/SearchItem");
		
		//按钮事件函数绑定
		cancelBtn.onClick.AddListener(delegate { CancelButtonClicked(); });
		searchBtn.onClick.AddListener(delegate { SearchButtonClicked(); });
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	private void CancelButtonClicked()
	{
		UnityFacade.Instance.UiManager.PopPanel();
	}

	private void SearchButtonClicked()
	{
		// 发送请求
		_searchFriendRequest.SendRequest(keyWordInputTextField.text);
		
	}

	public void HandleSearchFriendResponse(string json)
	{
		JsonData jsonData = JsonMapper.ToObject(json);
		List<User> userList = new List<User>();
		foreach (JsonData temp in jsonData["data"])
		{
			// 得到List<User>,动态实例化SearchItem
			int userId =(int) temp["userId"];
			string nick = temp["nick"].ToString();
			string avatar = temp["avatar"].ToString();
			User user = new User();
			user.UserId = userId;
			user.Nick = nick;
			user.Avatar = avatar;
			userList.Add(user);
		}
		
		
		// 动态实例化SearchItem
		SpawnSearchItem(userList);

	}

	/// <summary>
	/// 动态生成搜索结果项
	/// </summary>
	private void SpawnSearchItem(List<User> userList) 
	{
		//每次生成前先把已有的SearchItem清除了
		GameObject[] searchItems = GameObject.FindGameObjectsWithTag("SearchItem");
		foreach (GameObject temp in searchItems)
		{
			Destroy(temp);
		}
		
		//获得需要挂载的位置
		Transform v_layout_pos = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.SearchFriendPanel].transform.Find("Panel_Center/V_Layout");
		
		
		foreach (User temp in userList)
		{
			GameObject searchItemGo = GameObject.Instantiate(_searchItemPrefab, v_layout_pos, false);
			// 获得SearchItem组件，设置其代表的User对象，并刷新显示
			SearchItem si = searchItemGo.GetComponent<SearchItem>();
			si.RelatedUser = temp;
			si.SyncShow();

		}
		
	}
	
	
	public override void OnEnter()
	{
		if (!this.gameObject.activeSelf)
		{
			this.gameObject.SetActive(true);
		}
	}

	public override void OnPause()
	{
		
	}

	public override void OnResume()
	{
		
	}

	public override void OnExit()
	{
		this.gameObject.SetActive(false);
	}
}
